#encoding=utf-8
from __future__ import division

import sys
import os
import datetime
import time
import math
import ujson
import uuid
import urllib,urllib2
from urlparse import urlparse, parse_qsl

import requests
from django.contrib import auth
from django.template import RequestContext
from django.core.cache import cache
from django_redis import get_redis_connection
from django.core.servers.basehttp import FileWrapper
from django.http import StreamingHttpResponse
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import User
from django.db.models import Count, Max, F, Q
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from  xadmin.views.base import  CommAdminView,ModelAdminView, SortedDict, filter_hook
from django.views.generic import View
import xadmin
from websys.models import (
UserProfile, HXHUserInfo, HXHPayInfo,PlatformInfo,HXHUserLogin,HXHConsumerInfo,
AgentInfo,UserInfo,GameInfo,RoomInfo,
)

from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect,render
import requests,ujson,datetime,time
from websys.models import (
LotteryInfo,RoomInfo,UserInfo,IncrInfo,UserGamelog,TableInfo,PayInfo,Agent_Profit,Detaile_Profit
)
import timetool
from websys.function import check_sign
from websys import getlottory
from andy_manager import settings
from django.conf.urls import patterns, include, url


@csrf_exempt
def hxh_user_register(request):
    now = datetime.datetime.now()
    body = request.body
    data = ujson.loads(body)
    uid = data["uid"]
    pf = data["pf"]
    pf1 = data["pf1"]
    user_info = HXHUserInfo()
    user_info.uid = uid
    user_info.pf = pf
    user_info.pf1 = pf1
    user_info.body = body
    user_info.create_date = now
    user_info.save()

@csrf_exempt
def hxh_user_pay(request):
    now = datetime.datetime.now()
    body = request.body
    data = ujson.loads(body)
    order_id = data["order_id"]
    uid = data["uid"]
    money = data["money"]
    pay_info = HXHPayInfo()
    pay_info.order_id = order_id
    pay_info.uid = uid
    pay_info.money = money
    pay_info.body = body
    pay_info.create_date = now
    pay_info.save()

#对话框测试
@csrf_exempt
def testbox(request):
    return render(request, 'test_box.html', {'string': ''})


def testbox123(request,path):
    return render(request, str(path)+'.html', {'string': ''})

from django.contrib.admin.views.decorators import staff_member_required
@staff_member_required
def testpage(request):
    t_cont=RequestContext(request)
    t_init_cont=ModelAdminView.get_context
    print(t_init_cont,'---testpage------',t_cont)
    return render_to_response('my_template.html',  context_instance=t_init_cont)

    return render(request, 'xadmin/base_site.html', {'string': ''})

from django.contrib.admin.views.decorators import staff_member_required
from django.utils.text import capfirst
from xadmin.util import static, json, vendor, sortkeypicker
from adminx import AdminSettings
from xadmin.views.base import BaseAdminPlugin
from django.utils.translation import ugettext as _
from  xadmin.plugins.topnav import TopNavPlugin

class AboutView(CommAdminView):
    template_name = "my_template.html"
    #from myproject.admin_site import custom_admin_site
    # from andy_manager.admin_site import custom_admin_site
    # from django.contrib.admin import AdminSite
    # AdminSite.ge


    @filter_hook
    def get_nav_menu(self):

        self.admin_site = xadmin.site

        site_menu = (
                        {'title': '猎人游戏', 'perm': self.get_model_perm(HXHUserInfo, 'change'), 'menus':(
                            {'title': '玩家信息',  'url': self.get_model_url(HXHUserInfo, 'changelist') },
                            {'title': '消费信息', 'url': self.get_model_url(HXHConsumerInfo, 'changelist') },
                            {'title': '充值信息','url': self.get_model_url(HXHPayInfo, 'changelist') },
                            {'title': '登陆日志', 'url': self.get_model_url(HXHUserLogin, 'changelist') },
                            {'title': '用户信息', 'url': self.get_model_url(UserProfile, 'changelist')},
                        )},

                        {'title': '管理端', 'perm': self.get_model_perm(AgentInfo, 'change'), 'menus':(
                            {'title': '代理管理', 'url': self.get_model_url(AgentInfo, 'changelist')},
                            {'title': '代理结算', 'url': '/xadmin/about'},
                            {'title': '用户管理', 'url': self.get_model_url(UserInfo, 'changelist') },
                        )},

                        {'title': '游戏管理', 'perm': self.get_model_perm(GameInfo, 'change'), 'menus':(
                            {'title': '游戏列表', 'url': self.get_model_url(GameInfo, 'changelist')},
                            {'title': '房间管理', 'url': self.get_model_url(RoomInfo, 'changelist') },
                            {'title': 'Banner管理', 'url': self.get_model_url(PlatformInfo, 'changelist') },
                            {'title': '系统公告', 'url': self.get_model_url(PlatformInfo, 'changelist') },
                        )},
                    )
        # return None
        # self.admin_site = xadmin.site
        #site_menu = list(self.get_site_menu() or [])
        site_menu = list(site_menu or [])
        had_urls = []

        def get_url(menu, had_urls):
            if 'url' in menu:
                had_urls.append(menu['url'])
            if 'menus' in menu:
                for m in menu['menus']:
                    get_url(m, had_urls)
        get_url({'menus': site_menu}, had_urls)

        nav_menu = SortedDict()

        for model, model_admin in xadmin.site._registry.items():
            if getattr(model_admin, 'hidden_menu', False):
                continue
            app_label = model._meta.app_label
            app_icon = None
            model_dict = {
                'title': unicode(capfirst(model._meta.verbose_name_plural)),
                'url': self.get_model_url(model, "changelist"),
                'icon': self.get_model_icon(model),
                'perm': self.get_model_perm(model, 'view'),
                'order': model_admin.order,
            }
            if model_dict['url'] in had_urls:
                continue

            app_key = "app:%s" % app_label
            if app_key in nav_menu:
                nav_menu[app_key]['menus'].append(model_dict)
            else:
                # Find app title
                app_title = unicode(app_label.title())
                if app_label.lower() in self.apps_label_title:
                    app_title = self.apps_label_title[app_label.lower()]
                else:
                    mods = model.__module__.split('.')
                    if len(mods) > 1:
                        mod = '.'.join(mods[0:-1])
                        if mod in sys.modules:
                            mod = sys.modules[mod]
                            if 'verbose_name' in dir(mod):
                                app_title = getattr(mod, 'verbose_name')
                            elif 'app_title' in dir(mod):
                                app_title = getattr(mod, 'app_title')
                #find app icon
                if app_label.lower() in self.apps_icons:
                    app_icon = self.apps_icons[app_label.lower()]

                nav_menu[app_key] = {
                    'title': app_title,
                    'menus': [model_dict],
                }

            app_menu = nav_menu[app_key]
            if app_icon:
                app_menu['first_icon'] = app_icon
            elif ('first_icon' not in app_menu or
                    app_menu['first_icon'] == self.default_model_icon) and model_dict.get('icon'):
                app_menu['first_icon'] = model_dict['icon']

            if 'first_url' not in app_menu and model_dict.get('url'):
                app_menu['first_url'] = model_dict['url']

        for menu in nav_menu.values():
            menu['menus'].sort(key=sortkeypicker(['order', 'title']))

        nav_menu = nav_menu.values()
        nav_menu.sort(key=lambda x: x['title'])

        site_menu.extend(nav_menu)
        print nav_menu,"---************----nav_menu---view************----",site_menu
        return site_menu

    def get(self,request):
        print ('---get-----')
        xadmin.site.register_plugin(AccountMenuPlugin, self)
        xadmin.site.register_plugin(TopNavPlugin, self)
        return self.template_response("my_template.html",self.get_context())
        #return self.render_response(RequestContext(request))
    #return render_to_response('my_template.html',  context_instance=t_init_cont)





urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'jdb_manager.views.home', name='home'),
    # url(r'^jdb_manager/', include('jdb_manager.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
                        url(r'^xadmin/', include(xadmin.site.urls), name='xadmin'),
                        url(r'^captcha/', include('captcha.urls')),
                        url(r'^lottory/test', 'websys.views.test_fun', name='test'),
                        url(r'^lottory/grap', 'websys.views.lottory_grap', name='lottory_grap'),
                        url(r'^lottory/get_next_issue', 'websys.views.get_next_issue', name='get_next_issue'),
                        url(r'^lottory/get_issue/(.*)', 'websys.views.get_issue', name='get_issue'),
                        url(r'^lottory/get_latest_issue','websys.views.get_latest_issue',name='get_latest_issue'),
                        url(r'^lottory/get_room_info/(.*)$','websys.views.get_room_info',name='get_room_info'),
                        url(r'^lottory/register','websys.views.register',name='register'),
                        url(r'^lottory/login','websys.views.login',name='login'),
                        url(r'^lottory/get_user_info','websys.views.get_user_info',name='get_user_info'),
                        url(r'^lottory/incr_goldpoint','websys.views.incr_goldpoint',name='incr_goldpoint'),
                        url(r'^lottory/dec_goldpoint','websys.views.incr_goldpoint',name='incr_goldpoint'),
                        url(r'^lottory/report_gamelog','websys.views.report_gamelog',name='report_gamelog'),
                        url(r'^lottory/get_today_rankinfo','websys.views.get_today_rankinfo',name='get_today_rankinfo'),
                        url(r'^lottory/get_my_log','websys.views.get_my_log',name='get_my_log'),
                        url(r'^lottory/get_log','websys.views.get_log',name='get_log'),
                        url(r'^lottory/payinfo','websys.views.payinfo',name='payinfo'),
                        url(r'^lottory/get_record_by_issue_tableid','websys.views.get_record_by_issue_tableid',name='get_record_by_issue_tableid'),
                        url(r'^lottory/bind_agent','websys.views.bind_agent',name='bind_agent'),

)

# -*- coding:utf-8 -*-
# Create your views here.


#时间转换时间戳
def TimeToStamp(_times):
    #a = "2017-09-28 10:00:00"
    return time.mktime(time.strptime(_times,'%Y-%m-%d %H:%M:%S'))

#插入到开奖表中
def save_lottoryinfo(returnOBJ=0):
    import getlottory

    t_ok=0
    #t_obj=getlottory.getNewKeno8()
    url = 'http://139.199.200.238/api/home'
    data = urllib2.urlopen(url, timeout=5)
    get_infos = ujson.loads(data.read())
    ll=None
    #print('--lottory_grap--',t_obj)
    issue = int(get_infos['data']['Issue'])
    num_list = get_infos['data']['Num'].split('|')
    result = num_list[0]
    extra = num_list[1]
    open_time = get_infos['data']['PrizeTime']
    if get_infos:# and len(t_obj['ball'])>0:
     #获取数据库最新的期号
        last_item=LotteryInfo.objects.latest('id')
        last_id=None
        if last_item :
            last_id=last_item.issue
        this_id=issue
        if last_id==None or int(this_id)>int(last_id):

            ll=LotteryInfo()#res_data={'ball':[],'extra':[],'id':'','time':''}
            ll.extra=extra
            ll.result=result
            ll.issue=issue
            ll.open_time=open_time
            ll.save()
            t_ok=1
            ll=LotteryInfo.objects.get(pk=ll.pk)
    else:
        print('--not out...')
    if returnOBJ:
        return ll
    return t_ok


#获取开奖记录，9：15--23：55
@csrf_exempt
#@login_required(login_url="/xadmin/")
def lottory_grap(request):
    import getlottory
    ret = {"ret": 0, "msg": ""}
    tt=save_lottoryinfo()
    #2秒循环一次,分钟整除5则去抓取
    t_minute=time.strftime('%M',time.localtime(time.time()))
    print(tt,'--lottory_grap---',t_minute)
    t_sec=2
    t_hour_min=9
    t_hour_max=23
    t_ok=0
    while True:
        #print(t_minute,'>>>>>',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
        t_hour=int(time.strftime('%H',time.localtime(time.time())))
        t_minute=time.strftime('%M',time.localtime(time.time()))
        if t_hour>=t_hour_min and t_hour<=t_hour_max and int(t_minute)%5==0:
            if (not t_ok):
                t_ok=save_lottoryinfo()
                print(t_ok,time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))

        else:
            t_ok=0
            if t_hour<9:
                t_sec=60*10#10分钟一次
            else:
                t_sec=2
        time.sleep(t_sec)
    ret['minute']=t_minute
    return HttpResponse(ujson.dumps(ret))


# 获取下一局可开的ID和期数
#{"msg":"ok","data":{"type":1,"lottery_id":7436,"open_at_stamp":1497867600,"open_left_second":-30,"issue":"829680","open_at":"2017-06-19 18:20"},"ret":0}
@csrf_exempt
def get_next_issue(request):
    res_obj={"msg":"err","data":{},"ret":-1}
    t_type=request.GET['type']
    if not t_type:
        t_type=1
    all_item=LotteryInfo.objects.latest('id')
    cur_time=time.time()
    t_ll=None
    if all_item:
        last_item=all_item
        #判断时间在5分钟内
        print last_item,'---',last_item.open_time,type(last_item.open_time)
        tmp_sec=cur_time-timetool.datetime_toTimestamp(last_item.open_time)

        if tmp_sec<5*60:
            t_ll=last_item
        else:

            t_ll=save_lottoryinfo(1)

    else:
        t_ll=save_lottoryinfo(1)
    if t_ll:
        tmp_data={"type":t_type,"lottery_id":0,"open_at_stamp":0,"open_left_second":0,"issue":0,"open_at":''}
        tmp_data['lottery_id']=t_ll.pk+1
        #print(t_ll.open_time,'--t_ll.open_time---',type(t_ll.open_time))
        time_type=type(t_ll.open_time)
        next_time=t_ll.open_time+datetime.timedelta(minutes=5)
        tmp_data['open_at']=next_time.strftime('%Y-%m-%d %H:%M:%S')#加5分钟
        tmp_data['open_at_stamp']=timetool.datetime_toTimestamp(next_time)
        tmp_data['open_left_second']=int(tmp_data['open_at_stamp']-cur_time)
        #print t_ll.issue,'---t_ll.issue--',type(t_ll.issue)
        tmp_data['issue']=t_ll.issue+1
        res_obj['ret']=0
        res_obj['data']=tmp_data
    return HttpResponse(ujson.dumps(res_obj))




#获取开奖结果
#{"msg":"ok","issue":"829680","ret":0,"lottery_result":{"frisbee":"01","sorted_lottery_number":["22","09","63","36","45","71","62","25","60","06","41","13","57","20",
# "74","10","19","73","64","46"],"update_at":"2017-06-19 18:20:50","lottery_id":7436,"lottery_number":"62,71,13,46,41,73,19,57,25,74,10,36,20,64,60,09,63,45,06,22",
# "issue":"829680","open_at":"2017-06-19 18:20"}}
def get_issue(request,_issue):
    t_issue=_issue
    res_obj={"msg":"err",'issue':t_issue,"ret":-1}
    ll=None
    if not t_issue or t_issue=='':#获取最新的
        ll_arr=LotteryInfo.objects.latest('id')
        if ll_arr:
            ll=ll_arr
    #数据库是否有了
    elif LotteryInfo.objects.filter(issue=t_issue).exists():
        ll=LotteryInfo.objects.get(issue=t_issue)
    if ll:
        res_obj['ret']=0
        t_data={"frisbee":ll.extra,"lottery_id":ll.pk,"lottery_number":ll.result,"issue":ll.issue,"open_at":ll.open_time.strftime('%Y-%m-%d %H:%M:%S')}
        data = getlottory.SortList(ll.result)
        t_data['sorted_lottery_number'] = data
        res_obj['lottery_result']=t_data
        res_obj['msg'] = 'ok'
    return HttpResponse(ujson.dumps(res_obj))


#测试陈函数
@csrf_exempt
def test_fun(request):
    res_obj={"msg":"err","ret":-1}
    ri=RoomInfo()
    res_obj['ret']=ri.save()
    return HttpResponse(ujson.dumps(res_obj))


#判断传入的值是否为数字，195行用到
@csrf_exempt
def checkint(a,b,c):
    l = [a,b,c]
    n = 0
    for i in l:
        if str(i).isdigit():
            n +=1
    return n


#判断get方式传的参数名是否正确

def check_args(args,args2):
    n = 0
    for i in args:
        if i in args2:
            n +=1
    return n




#获取最新的快乐8期号和结果
@csrf_exempt
def get_latest_issue(request):
    import json
    res_obj = {'msg':'err','issue':'','ret':-1}
    t_obj = request.GET.dict()
    data = t_obj.keys()
    values = t_obj.values()
    str_values =json.dumps(values)
    api_list = ['tableid','type','lottery_id']
    if check_args(data,api_list) ==len(api_list) :#判断传入的接口参数是否与['tableid','type','lottery_id']相符
        t_lottery_id = request.GET['lottery_id']
        t_tableid = request.GET['tableid']
        t_type = request.GET['type']
        result = checkint(t_lottery_id, t_tableid, t_type)#判断传入的值是否为数字
        if result==3:#如果两者都满足则返回最新期号
            last_data = LotteryInfo.objects.latest('id')
            if int(t_lottery_id) == last_data.id:
                if int(t_type) in [1,2,3]:
                    res_obj['msg'] = 'ok'
                    res_obj['issue'] = last_data.issue
                    res_obj['ret'] = 0
                    lottery_result = {'frisbee':last_data.extra,'open_at':time.strftime('%Y-%m-%d %H:%M:%S'),'lottery_number':last_data.result,'issue':last_data.issue,'lottery_id':int(t_lottery_id),'type':int(t_type),'update_at':last_data.open_time.strftime('%Y-%m-%d %H:%M:%S')}
                    datas = getlottory.SortList(last_data.result)
                    lottery_result['sorted_lottery_number'] = datas
                    res_obj['lottery_result'] = lottery_result
                    return HttpResponse(ujson.dumps(res_obj))
                else:
                    err_msg = {"msg": "game type give error", "ret": -1}
                    return HttpResponse(ujson.dumps(err_msg))
            else:
                err_msg = {"msg": "lottery_id give error","ret": -1}
                return HttpResponse(ujson.dumps(err_msg))
        else:
            err_msg = {"msg": "args give error", "ret": -1}
            return HttpResponse(ujson.dumps(err_msg))
    else:
        err_msg = {"msg": "args.values give error","ret": -1}
        return HttpResponse(ujson.dumps(err_msg))


#获取房间信息
# {"data":[{"min_join_gold":100,"player_bet_time":60,"name":"\u5929\u4e0a\u4eba\u95f4",
#           "grab_master_bets":[10,50,100],"sweep_profit_percent":7,
#           "player_bets":[10,50,100,500],"tables":[9,8,5,11],"min_master_gold":100,
#           "normal_profit_percent":6,"grab_master_time":60,"room_id":13,"master_percent":5,
#           "master_choose_seat_time":10,"table_max_player":30,"table_fee":20,"room_type":3,
#           "player_max_bet_times":1}],"gametype":3,"ret":0}
@csrf_exempt
def get_room_info(request,_room_type):
    t_type = _room_type
    res_obj = {'type':t_type,'ret':-1,'data':''}
    if  not t_type or int(t_type)==1 or t_type==None:#如果传入的房间号或者为1为空则默认返回北京快8的信息
        room_infos = RoomInfo.objects.filter(room_type=1)
        info_list = []
        for i in room_infos:#拿到所有游戏类型为1的房间信息
            grab_master_bets=map(int,i.grab_master_bets.split(','))
            # tables= []
            # tables.append(int(i.tables))
            tables=map(int,i.grab_master_bets.split(','))
            player_bets = map(int,i.tables.split(','))
            room_info = {'min_join_gold':i.min_join_gold,'player_bet_time':i.player_bet_time,'name':i.name,
                         'grab_master_bets':grab_master_bets,'sweep_profit_percent':i.sweep_profit_percent,
                         'player_bets':player_bets,'tables':tables,'min_master_gold':i.min_master_gold,
                         'normal_profit_percent':i.normal_profit_percent,'grab_master_time':i.grab_master_time,
                         'room_id':i.id,'master_percent':i.master_percent,'master_choose_seat_time':i.master_choose_seat_time,
                         'table_max_player':i.table_max_player,'table_fee':i.table_fee,'room_type':i.room_type,
                         'player_max_bet_times':i.player_max_bet_times}
            info_list.append(room_info)
        res_obj['ret']= 0
        res_obj['type'] = 1
        res_obj['data'] = info_list
        return HttpResponse(ujson.dumps(res_obj))
    else:
        res_obj['ret']=0
        res_obj['type'] = t_type
        res_obj['data'] = []
        return HttpResponse(ujson.dumps(res_obj))


#玩家注册
@csrf_exempt
def register(request):
    Method = request.method
    if Method == 'POST':
        account = request.POST['account']
        passwd = request.POST['password']
        icon = request.POST['icon']
        nickname=request.POST['nickname']
        agent_account=request.POST['agent_account']
        t_obj = request.POST.dict()
        ss = t_obj['account']
        if len(str(nickname))>6 and len(str(nickname))<2:
            objs = {'msg': '账号长度不符!', 'ret': -6}
            return HttpResponse(ujson.dumps(objs))
        if check_sign(t_obj):#判断签名
            infos = UserInfo.objects.filter(uid=account).count()#判断该账户是否已经存在
            nickname_info=UserInfo.objects.filter(nickname=nickname).count()
            if not AgentInfo.objects.filter(account=agent_account).exists():
                objs = {'msg': '代理账号不存在!', 'ret': -5}
                return HttpResponse(ujson.dumps(objs))
            agent_info = AgentInfo.objects.get(account=agent_account)
            if nickname_info>0:
                objs = {'msg': '昵称已经存在!', 'ret': -1}
                return HttpResponse(ujson.dumps(objs))
            if infos>0:
                objs = {'msg':'账号已经存在!','ret':-2}
                return HttpResponse(ujson.dumps(objs))
            else:
                info = UserInfo(uid=account,password=passwd,head_img=icon,gamepoint=0,nickname=nickname,agentid_id=agent_info.id)#保存账户
                info.save()
                data = {'goldpoint': info.gamepoint, 'account': info.uid,
                        'user_id': info.id, 'icon': info.head_img,'agent_id':info.agentid_id,'nickname':info.nickname}
                objs = {'msg': '注册成功!', 'ret': 0,'user_info':data}
                return HttpResponse(ujson.dumps(objs))
        else:
            objs = {'msg': 'sign error', 'ret': -3}
            return HttpResponse(ujson.dumps(objs))
    else:
        objs = {'msg': 'request method error', 'ret': -4}
        return HttpResponse(ujson.dumps(objs))


#玩家登陆
@csrf_exempt
def login(request):
    Method = request.method
    if Method == 'POST':
        passwd = request.POST['password']
        account = request.POST['account']
        t_obj = request.POST.dict()
        if check_sign(t_obj):  # 判断签名
            infos = UserInfo.objects.filter(uid=account).count()  # 判断该账户是否已经存在
            if infos > 0:
                db_user = UserInfo.objects.get(uid=account)
                if db_user.password==passwd:
                    data = {'goldpoint': db_user.gamepoint, 'account': db_user.uid,
                            'user_id': db_user.id, 'icon': db_user.head_img,'agent_id':db_user.agentid_id,'nickname':db_user.nickname}
                    objs = {'msg': '登录成功!', 'ret': 0,'user_info':data}
                    return HttpResponse(ujson.dumps(objs))
                else:
                    objs = {'msg': '密码错误!', 'ret': -1}
                    return HttpResponse(ujson.dumps(objs))
            else:
                objs = {'msg': '账号不存在!', 'ret': -1}
                return HttpResponse(ujson.dumps(objs))
        else:
            objs = {'msg': 'sign error', 'ret': -1}
            return HttpResponse(ujson.dumps(objs))
    else:
        objs = {'msg': 'request method error', 'ret': -1}
        return HttpResponse(ujson.dumps(objs))


#获取玩家信息
@csrf_exempt
def get_user_info(request):
    Method = request.method
    t_msg = {'msg':'error','ret':-1,'user_info':''}
    if Method=='POST':
        userid = request.POST['user_id']
        t_obj = request.POST.dict()
        if check_sign(t_obj):
            ids = UserInfo.objects.filter(id=userid).count()  # 判断该ID是否已经存在
            if ids>0:
                user_infos = UserInfo.objects.get(id=userid)
                t_msg['msg'] = 'OK'
                t_msg['ret'] = 0
                data = {'goldpoint':user_infos.gamepoint,'account':user_infos.uid,
                        'user_id':user_infos.id,'icon':user_infos.head_img,'agent_id':user_infos.agentid_id,'nickname':user_infos.nickname}
                t_msg['user_info'] = data
                return HttpResponse(ujson.dumps(t_msg))
            else:
                t_msg['msg'] = 'user_id not exist'
                return HttpResponse(ujson.dumps(t_msg))
        else:
            infos = {'msg':'sign error','ret':-1}
            return HttpResponse(ujson.dumps(infos))
    else:
        objs = {'msg': 'request method error', 'ret': -1}
        return HttpResponse(ujson.dumps(objs))


#在游戏增加(或减)玩家游戏金币
import json
@csrf_exempt
def incr_goldpoint(request):
    Method = request.method
    print '-------------dec-----------'
    if Method =='POST':
        info_dict = request.POST.dict()
        lottery_id = info_dict['lottery_id']
        issue = info_dict['issue']
        table_id = info_dict['table_id']
        user_id = info_dict['user_id']
        amounts = info_dict['amount']
        remark = info_dict['remark']
        game_type = info_dict['game_type']
        print lottery_id,'---------------lottory----------'
        if check_sign(info_dict):
            amount = amounts.encode('utf-8')
            #if type(eval(amount)) == float:
            if amount > 0:#如果amount大于0则增加玩家游戏金币
                user_infos = UserInfo.objects.get(id=user_id)
                before_gold = user_infos.gamepoint
                after_gold = int(before_gold) + int(amount)
                UserInfo.objects.filter(id=user_id).update(gamepoint=after_gold)
                user_info = UserInfo.objects.get(id=user_id)
                golds = user_info.gamepoint
                IncrInfo.objects.create(lottery_id=int(lottery_id),issue=int(issue),table_id=int(table_id),user_id=(user_id),
                                        amount=amount,changed_gold=int(golds),remark=remark,game_type=int(game_type))
                objs = {'msg':'+success','goldpoint':float(golds),'ret':0}
                print objs
                return HttpResponse(ujson.dumps(objs))
            elif amount < 0:#如果amount小于0则减玩家游戏金币
                user_infos = UserInfo.objects.get(id=user_id)
                before_gold = user_infos.gamepoint
                after_gold = float(int(before_gold)) + float(amount)
                UserInfo.objects.filter(id=user_id).update(gamepoint=after_gold)
                user_info = UserInfo.objects.get(id=user_id)
                golds = user_info.gamepoint
                IncrInfo.objects.create(lottery_id=int(lottery_id),issue=int(issue),table_id=int(table_id),user_id=(user_id),
                                        amount=amount, changed_gold=int(golds), remark=remark,game_type=int(game_type))
                objs = {'msg':'-success','goldpoint':float(golds),'ret':0}
                print objs
                return HttpResponse(ujson.dumps(objs))
            else:
                objs = {'msg': 'amount give error ！', 'ret': -1}
                return HttpResponse(ujson.dumps(objs))
        else:
            objs = {'msg':'sign error','ret':-1}
            return HttpResponse(ujson.dumps(objs))
    else:
        objs = {'msg': 'request method error', 'ret': -1}
        return HttpResponse(ujson.dumps(objs))



#上传游戏日志数据
@csrf_exempt
def report_gamelog(request):
    import json
    Method = request.method
    if Method == 'POST':
        post_data = request.POST.dict()#{'data,'sign':'''}
        print post_data
        if check_sign(post_data):
            data=json.loads(post_data['data'])
           # print '-------1---------',data
            for i_issue in data:
                cur_data = data[i_issue]
                #print '----------------2-----------',cur_data
                for tb_id in cur_data:
                    u_data=cur_data[tb_id]['user_infos']
                    objs = {'msg': 'sucess', 'ret': 0, 'user_infos': {}}
                    tb_data = cur_data[tb_id]['table_infos']
                    master_fee = tb_data['master_fee']
                    table_fee = tb_data['table_fee']
                    profit_fee = tb_data['profit_fee']
                    for ii_u in u_data:
                        print ii_u
                        tmp_data=u_data[ii_u]
                        is_master =tmp_data['is_master']
                        gain_goldpoint=tmp_data['gain_goldpoint']
                        bet_places = str(tmp_data['bet_places'])
                        u=UserInfo.objects.get(id=ii_u)
                        u.gamepoint += tmp_data['gain_goldpoint']
                        u.save()
                        UserGamelog.objects.create(issue=i_issue,table_id=tb_id,user_id=ii_u,is_master=is_master,
                                                   gain_goldpoint=gain_goldpoint,bet_places=bet_places)
                        user_data = UserInfo.objects.get(id=ii_u)
                        dic_info = {str(ii_u):{'goldpoint':user_data.gamepoint,'account':user_data.uid,
                                              'user_id':user_data.id,'icon':user_data.head_img}}
                        objs['user_infos'].update(dic_info)
                        if int(is_master)==1:
                            if  UserInfo.objects.get(pk=ii_u).agentid_id:
                                if int(profit_fee) != 0:
                                    agentid=UserInfo.objects.get(pk=ii_u).agentid_id
                                    agent_info = AgentInfo.objects.get(id=agentid)
                                    detaile_info =Detaile_Profit()
                                    detaile_info.uid_id=u.id
                                    detaile_info.account=u.uid
                                    detaile_info.agent_account=agent_info.account
                                    detaile_info.agent_profit=int(profit_fee)
                                    detaile_info.issue=i_issue
                                    detaile_info.save()
                                    if agent_info.status and agent_info.ischeck:
                                        agent_info.allmoney +=int(profit_fee)
                                        agent_info.save()
                                        date = datetime.datetime.now().strftime("%Y-%m-%d")
                                        if Agent_Profit.objects.filter(agentid_id=agent_info.id,date=date).exists():
                                            profit_info =Agent_Profit.objects.get(agentid_id=agent_info.id,date=date)
                                            profit_info.profit +=int(profit_fee)
                                            profit_info.save()
                                        else:
                                            profit_infos=Agent_Profit()
                                            profit_infos.agentid_id=agent_info.id
                                            profit_infos.account=agent_info.account
                                            profit_infos.profit=int(profit_fee)
                                            profit_infos.save()

                    TableInfo.objects.create(issue=i_issue,table_id=tb_id,master_fee=master_fee,
                                             table_fee=table_fee,profit_fee=profit_fee)
                    return HttpResponse(ujson.dumps(objs))
        else:
            objs = {'msg':'sign error','ret':-1}
            return HttpResponse(ujson.dumps(objs))
    else:
        objs = {'msg': 'request method error', 'ret': -1}
        return HttpResponse(ujson.dumps(objs))



#获取今日排名
@csrf_exempt
def get_today_rankinfo(request):
    objs = {'rank_three':[],'my_info':{'gain_goldpoint':0,'rank':-1}}
    dics = request.GET.dict()
    if  not dics or dics.keys()[0] !='user_id' or not dics.values()[0]:
        list_info = []
        dic = {}
        golds_list=[]
        all_infoss = UserGamelog.objects.filter(create_time__gte=datetime.date.today())
        id_list = []
        for all_user_ids in all_infoss:
            all_user_id = int(all_user_ids.user_id)
            if not all_user_id in id_list:
                id_list.append(all_user_id)
        for i in id_list:
            all_info = all_infoss.filter(user_id=i)
            each_gold = 0
            for items in all_info:
                each_gold += int(items.gain_goldpoint)
                dic ={}
            dic[each_gold] = i
            golds_list.append(dic)
        r = 0
        dics = {}
        gold_list =sorted(golds_list)
        while r < len(golds_list):
            if not gold_list[-1].values()[0] in dics.values():
                o = gold_list[-1]
                p =o.keys()[0]
                dics[p] = gold_list[-1].values()[0]
                gold_list.pop(-1)
                r +=1
                continue
            else:
                gold_list.pop(-1)
                r +=1
                continue
        info_dic = {}
        n = 0
        k = 1
        lens = len(dics)
        lenth = lens
        while n <lenth:
            user_idss =dics[max(dics.keys())]
            infos = UserInfo.objects.get(id=user_idss)
            info_dic['account'] = infos.uid
            info_dic['user_id'] = infos.id
            info_dic['goldpoint'] = infos.gamepoint
            info_dic['rank'] = k
            info_dic['gain_goldpoint'] = max(dics.keys())
            info_dic['icon'] = infos.head_img
            info_dic['nickname']=infos.nickname
            list_info.append(info_dic)
            del dics[max(dics.keys())]
            info_dic = {}
            n +=1
            k +=1
            continue
        objs['my_info'] = {'gain_goldpoint': 0, 'rank': -1}
        objs['rank_three'] = list_info[:3]
        return HttpResponse(ujson.dumps(objs))
    else:
        user_ids = request.GET['user_id'].decode('utf-8')
        user_id = eval(user_ids)
        datass = UserGamelog.objects.filter(user_id=user_id)
        datas = datass.filter(create_time__gte=datetime.date.today())
        golds = 0
        for i in datas:
            golds += i.gain_goldpoint
        list_info = []
        dic = {}
        golds_list=[]
        all_infoss = UserGamelog.objects.filter(create_time__gte=datetime.date.today())
        id_list = []
        for all_user_ids in all_infoss:
            all_user_id = int(all_user_ids.user_id)
            if not all_user_id in id_list:
                id_list.append(all_user_id)
        for i in id_list:
            all_info = all_infoss.filter(user_id=i)
            each_gold = 0
            for items in all_info:
                each_gold += int(items.gain_goldpoint)
                dic ={}
            dic[each_gold] = i
            golds_list.append(dic)
        r = 0
        dics = {}
        gold_list =sorted(golds_list)
        while r < len(golds_list):
            if not gold_list[-1].values()[0] in dics.values():
                o = gold_list[-1]
                p =o.keys()[0]
                dics[p] = gold_list[-1].values()[0]
                gold_list.pop(-1)
                r +=1
                continue
            else:
                gold_list.pop(-1)
                r +=1
                continue
        info_dic = {}
        n = 0
        k = 1
        rank = -1
        lens = len(dics)
        lenth = lens
        while n <lenth:
            user_idss =dics[max(dics.keys())]
            if user_idss == user_id:
                rank = k
            infos = UserInfo.objects.get(id=user_idss)
            info_dic['account'] = infos.uid
            info_dic['user_id'] = infos.id
            info_dic['goldpoint'] = infos.gamepoint
            info_dic['rank'] = k
            info_dic['gain_goldpoint'] = max(dics.keys())
            info_dic['icon'] = infos.head_img
            info_dic['nickname'] = infos.nickname
            list_info.append(info_dic)
            del dics[max(dics.keys())]
            info_dic = {}
            n +=1
            k +=1
            continue
        objs['my_info'] = {'gain_goldpoint': golds, 'rank': rank}
        objs['rank_three'] = list_info[:3]
        return HttpResponse(ujson.dumps(objs))


#获取玩家当天投注的历史信息
@csrf_exempt
def get_my_log(request):
    objs = {'msg':'error','ret':-1,'lottery_logs':[],'issue_results':{}}
    id_dic = request.GET.dict()
    keys_list = id_dic.keys()
    agrs = ['user_id']
    datas = []
    if check_args(keys_list,agrs) == len(agrs):
        user_id = request.GET['user_id']
        counts = UserGamelog.objects.filter(user_id=user_id).count()
        if counts > 0:
            game_logs = UserGamelog.objects.filter(user_id=user_id)
            today_log = game_logs.filter(create_time__gte=datetime.date.today())
            data = []
            for items in today_log:
                if items.is_master ==1:
                    data.append(str(items.issue))
                    data.append(True)
                    data.append(items.gain_goldpoint)
                    data.append(eval(str(items.bet_places)))
                    datas.append(data)
                    data=[]
                else:
                    data.append(str(items.issue))
                    data.append(False)
                    data.append(items.gain_goldpoint)
                    data.append(eval(str(items.bet_places)))
                    datas.append(data)
                    data=[]
            time_issue = LotteryInfo.objects.filter(create_time__gte=datetime.date.today())
            all_issue = time_issue.order_by('-id')[:40]
            results ={}
            for i in all_issue:
                results[str(i.issue)] = str(i.result)
            objs['issue_results'] = results
            objs['lottery_logs'] = datas
            objs['msg'] = 'success'
            objs['ret'] = 0
            print 'success'
            return HttpResponse(ujson.dumps(objs))
        else:
            print ' not exist'
            obj = {'msg':'今天没有投注信息或该账户不存在','ret':-1}
            return HttpResponse(ujson.dumps(obj))
    else:
        print 'agrs error'
        obj = {'msg':'接口参数名错误','ret':-1}
        return HttpResponse(ujson.dumps(obj))



#根据期号和桌号获取玩家记录
@csrf_exempt
def get_log(request):
    dicts = request.GET.dict()
    keys = dicts.keys()
    infos = ['issue','table_id']
    objs = {'msg':'error','ret':-1,'issue_log':{},'table_log':{}}
    if check_args(keys,infos) == len(infos):
        issue = request.GET['issue']
        table_id = request.GET['table_id']
        iss_count = UserGamelog.objects.filter(issue=issue).count()
        tab_count = UserGamelog.objects.filter(table_id=table_id).count()
        data = {}
        datas= {}
        if iss_count > 0 and tab_count > 0:
            infos = UserGamelog.objects.filter(issue=issue)
            info = UserGamelog.objects.filter(table_id=table_id)
            for items in infos:
                if items.is_master==1:
                    data[str(items.issue)] = [str(items.issue), True, items.gain_goldpoint, eval(str(items.bet_places))]
                else:
                    data[str(items.issue)] = [str(items.issue), False, items.gain_goldpoint, eval(str(items.bet_places))]
            for item in info:
                if item.is_master==1:
                    datas[str(item.issue)] = [str(item.issue), True, item.gain_goldpoint, eval(str(item.bet_places))]
                else:
                    datas[str(item.issue)] = [str(item.issue), True, item.gain_goldpoint, eval(str(item.bet_places))]
            objs['msg'] = 'success'
            objs['ret'] = 0
            objs['issue_log'] = data
            objs['table_log'] = datas
            return HttpResponse(ujson.dumps(objs))
        else:
            obj = {'msg': '该期或该桌没有该玩家的记录', 'ret': -1}
            return HttpResponse(ujson.dumps(obj))
    else:
        obj = {'msg':'接口参数名错误','ret':-1}
        return HttpResponse(ujson.dumps(obj))


#玩家订单充值
@csrf_exempt
def payinfo(request):
    Method = request.method
    if Method == 'POST':
        dicts = request.POST.dict()
        if check_sign(dicts):
            order_id = dicts['order_id']
            user_id = dicts['user_id']
            goldpoint = dicts['goldpoint']
            counts = PayInfo.objects.filter(order_id=str(order_id)).count()
            if counts ==0:
                PayInfo.objects.create(order_id=order_id,user_id=user_id,goldpoint=goldpoint)
                objs = {'msg':'success','code':0}
                return HttpResponse(ujson.dumps(objs))
            else:
                objs = {'msg':'order_id aready exits','code':-1}
                return HttpResponse(ujson.dumps(objs))
        else:
            objs = {'msg':'sign error','code':-1}
            return HttpResponse(ujson.dumps(objs))
    else:
        objs = {'msg':'request method error','code':-1}
        return HttpResponse(ujson.dumps(objs))



#根据issue，table_id获取当期桌号下的所有玩家牌局记录
def get_record_by_issue_tableid(request):
    dicts = request.GET.dict()
    l = ['sign','issue','table_id']
    objs = {'records':[],'lottery_number':[],'ret':-1}
    if check_sign(dicts):
        key_list = dicts.keys()
        if  key_list !=[] and check_args(key_list,l)==len(l):
            issue = dicts['issue']
            table_id = dicts['table_id']
            counts = UserGamelog.objects.filter(table_id=table_id).filter(issue=issue).count()
            if counts !=0:
                datas = UserGamelog.objects.filter(table_id=table_id).filter(issue=issue)
                records_list = []
                for i in datas:
                    if i.is_master==1:
                        records_list.append(True)
                        records_list.append(i.gain_goldpoint)
                        records_list.append(i.bet_places)
                        u_account = UserInfo.objects.get(id=i.user_id).uid
                        records_list.append(u_account)
                        objs['records'].append(records_list)
                        records_list = []
                    else:
                        records_list.append(False)
                        records_list.append(i.gain_goldpoint)
                        records_list.append(i.bet_places)
                        u_account = UserInfo.objects.get(id=i.user_id).uid
                        records_list.append(u_account)
                        objs['records'].append(records_list)
                        records_list = []
                i_result = LotteryInfo.objects.get(issue=issue).result.split(',')[:10]
                result_list = []
                for j in i_result:
                    result_list.append(j)
                objs['lottery_number'] = result_list
                objs['ret'] = 0
                print objs,'=======-=-=-=-=-'
                return HttpResponse(ujson.dumps(objs))
            else:
                return HttpResponse(ujson.dumps(objs))
        else:
            objs = {'msg':' parm error','ret':-1}
            return HttpResponse(ujson.dumps(objs))
    else:
        objs = {'msg':'sign error','ret':-1}
        return HttpResponse(ujson.dumps(objs))



#绑定代理
#/api/lottery/bind_agent?sign=xx&uid=xx&agent_account=xx
@csrf_exempt
def bind_agent(request):
    data ={'code':-1,'msg':''}
    dicts = request.GET.dict()
    l = ['sign','uid', 'agent_account']
    if check_sign(dicts):
        key_list=dicts.keys()
        if key_list != [] and check_args(key_list, l) == len(l):
            uid=dicts['uid']
            agent_account=dicts['agent_account']
            if AgentInfo.objects.filter(account=agent_account).exists():
                agent_id=AgentInfo.objects.get(account=agent_account).id
                user_info = UserInfo.objects.get(uid=uid)
                if not user_info.agentid_id:
                    user_info.agentid_id=agent_id
                    user_info.save()
                    data['msg'] = 'success'
                    data['code'] = 0
                    return HttpResponse(ujson.dumps(data))
                else:
                    data['msg'] = 'user exist agent'
                    data['code'] = -4
                    return HttpResponse(ujson.dumps(data))
            else:
                data['msg'] = 'agent not exist'
                data['code'] = -2
                return HttpResponse(ujson.dumps(data))
        else:
            data['msg'] = 'parm error'
            data['code'] = -3
            return HttpResponse(ujson.dumps(data))
    else:
        data['msg']='sign error'
        data['code']=-4
